package com.warpcode.gpsloggerlite;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import android.content.Context;
import android.os.Environment;


public class KMLWriter
{
	LocationDatabase db;       
	FileWriter out;
	
	private static final String KML_LOCATION = "/GPS Logger/KML";
	private static final String KML_EXTENSION = ".kml";
        
	public KMLWriter(Context context,String value)
	{
		db = new LocationDatabase(context);              
		try 
		{
			File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + KML_LOCATION);
			dir.mkdirs();
			if (Environment.getExternalStorageDirectory().canWrite()) 
			{
				out = new FileWriter(new File(dir+"/"+ value + KML_EXTENSION));
			}
			else
				throw new IOException();        
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
       
	public void write()
	{   
		Vector<String[]> matrix = db.getLocationsMatrix(); 
		try
		{
			out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
					+ "\n"
					+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\">"
					+ "\n" + "<Folder>" + "\n");
			for (int i = 0; i < matrix.size(); i++) 
			{   
				out.write("<Placemark>" + "\n"
						+ "<name> Point "
						+ (i+1)
						+ "</name>"
						+ "\n"
						+ "<description>"
						+ matrix.get(i)[0]
						+ "</description>"
						+ "\n"
						+ "<Point>"
						+ "\n"
						+ "<coordinates>"
						+ matrix.get(i)[2] 
						+ ","
						+ matrix.get(i)[1] 
						+ ","
						+ matrix.get(i)[3]
						+ "</coordinates>"
						+ "\n"
						+ " </Point>"
						+ "\n"
						+ "</Placemark>" + "\n");
			}
			out.write("</Folder>" + "\n" + "</kml>");
			out.close();
			db.close();
		}
		catch(IOException e)
		{
			e.printStackTrace(); 
		}
	}
}